package com.chensi.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.chensi.model.User;
import com.chensi.service.IUserService;
import com.chensi.util.JedisUtils;

@Controller
@RequestMapping("user")
public class UserController
{
	private static final Logger log=Logger.getLogger(UserController.class);
	@Autowired
	private IUserService userService;
	
	@RequiresPermissions(value="user:getUser")
	@RequestMapping("getUser")  
    public String toIndex(HttpServletRequest request,Model model) throws Exception{
		User user=null;
		if(request.getParameter("id")!=null){
			int userId = Integer.parseInt(request.getParameter("id"));  
	        user = this.userService.get(userId);  
		}
		if(request.getParameter("username")!=null){
			User entity=new User();
			entity.setName(request.getParameter("username"));
			user = this.userService.getByEntity(entity);
		}
        model.addAttribute("user", user);  
        return "/WEB-INF/jsp/user"; 
	}
	
	/**
	 * shiro方法授权注解,Value为SimpleAuthorizationInfo拥有的角色role
	 */
	@RequiresRoles(value="user")
	@RequestMapping("main")  
	public String main(HttpSession session){
		return "/WEB-INF/jsp/user";
	}
	
	@RequestMapping("noAuth")  
	public String noAuth(){
		return "redirect:/error/noAuth.do";
	}
	
	/**
	 * shiro方法授权注解,Value为SimpleAuthorizationInfo拥有的权限permission
	 */
	@RequiresPermissions(value="user:getJson")
	@RequestMapping("getUserJson")
	@ResponseBody
	public Map<String, Object> getJson(){
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("name", "admin");
		return map;
	}
	
	@RequestMapping("getString")
	@ResponseBody
	public String getString(){
		return "大大";
	}
	
	
	@RequestMapping(value="login")
	public String login(){
		return "/WEB-INF/jsp/login";
	}
	
	@RequestMapping(value="/doLogin",method=RequestMethod.POST)
	public ModelAndView doLogin(HttpServletRequest request,String username,String password){
		Subject subject=SecurityUtils.getSubject();
		UsernamePasswordToken token=new UsernamePasswordToken();
		token.setUsername(username);
		token.setPassword(password.toCharArray());
		//capthca检查
		String capthca = (String)subject.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		log.info("验证码kaptcha="+capthca);
		try
		{
			subject.login(token);
			log.info("登录认证成功");
			Session session=subject.getSession();
			Object o=session.getAttribute("beforeLogin");
			if(o!=null){
				log.info("跳往登录前页面");
				return new ModelAndView("redirect:"+o.toString());
			}
			return new ModelAndView("redirect:/user/main.do");
		} catch (AuthenticationException e)
		{
			log.error("登录认证失败");
			return new ModelAndView("/WEB-INF/jsp/login");
		}
	}
	
	@RequestMapping("getRedisString")
	@ResponseBody
	public Map<String, Object> getRedisString(){
		String str=userService.getRedisString();
		HashMap map = new HashMap();
		map.put("string", str);
		return map;
	}
	
	@RequestMapping("getRedisList")
	@ResponseBody
	public Map<String, Object> getRedisList(){
		Map<String, Object> map=new HashMap<String, Object>();
		List<User> list= userService.getRedisObjectList();
		map.put("users", list);
		return map;
	}
	
	@RequestMapping("getRedisObject")
	@ResponseBody
	public Map<String, Object> getRedisObject(Integer id){
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("user", userService.getRedisObject(id));
		return map;
	}
	
	@RequestMapping("updateUser")
	@ResponseBody
	public Map<String, Object> updateUser(){
		Map<String, Object> map=new HashMap<String, Object>();
		User u=new User("sisi",12,13665555);
		userService.update(u);
		return map;
	}
	
	@RequestMapping("addUser")
	@ResponseBody
	public Map<String, Object> addUser(@Valid User u,BindingResult br){
		Map<String, Object> map=new HashMap<String, Object>();
		if(br.hasErrors()){
			map.put("msg", br.getAllErrors().get(0).getDefaultMessage());
			return map;
		}
		userService.save(u);
		return map;
	}
	
	@RequestMapping("delUser")
	@ResponseBody
	public Map<String, Object> delUser(Integer id){
		Map<String, Object> map=new HashMap<String, Object>();
		userService.remove(id);
		return map;
	}
	
	@RequestMapping("getAllKey")
	@ResponseBody
	public Map<String, Object> getAllKey(){
		Map<String, Object> map=new HashMap<String, Object>();
		List<String> list=JedisUtils.getAllKey();
		map.put("key", list);
		for(String s:list){
			System.out.println(s);
		}
		return map;
	}
	
	/**
	 * freemarker渲染
	 * @return
	 */
	@RequestMapping("/fMain")  
	public String fMain(){
		return "/front/userIndexForFreemarker";
	}
}
